//
//  PageViewController.swift
//  demo
//
//  Created by HAip on 2020/2/19.
//  Copyright © 2020 CodeYu. All rights reserved.
//

import UIKit

//简单的实现滑动切换视图，即轮播图


class PageViewController: UIViewController {
    
    typealias PageScrollToIndexCallBack = (_ index: Int)->Void
    
    var pageScrooCallBack : PageScrollToIndexCallBack?
    
     // 数据源
    fileprivate var viewControllers: [UIViewController] = []
    fileprivate var currentIndex: Int = 0
    
    // 是否可以横向滑动 默认为NO
    var isAllowPageScroll: Bool{
        set{
            for subView in pageViewController.view.subviews {
                if subView.isKind(of: UIScrollView.self) {
                    (subView as! UIScrollView).isScrollEnabled = newValue
                }
            }
            
        }
        get{
            var scrollEnabled = false
            for subView in pageViewController.view.subviews {
                           if subView.isKind(of: UIScrollView.self) {
                            scrollEnabled =   (subView as! UIScrollView).isScrollEnabled
                            break
                    }
            }
            return scrollEnabled
        }
    }
    
    
    
    // 懒加载创建UIPageViewController
  fileprivate  lazy var pageViewController: UIPageViewController = {
        //设置水平滑动
        let pageVc = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        
        pageVc.dataSource = self
        pageVc.delegate = self
        return pageVc
    }()
    


    override func viewDidLoad() {
        super.viewDidLoad()
        addPageViewController()
        isAllowPageScroll = false // 默认不可滑动


        // Do any additional setup after loading the view.
    }
    
    fileprivate  func addPageViewController() {
        self.addChild(pageViewController)
        pageViewController.view.frame = self.view.frame
        view.addSubview(pageViewController.view)
        pageViewController.didMove(toParent: self)
    }
    
    func updateDataSource(controllers: [UIViewController]){
        viewControllers = controllers
        // 设置初始化显示视图控制器
        pageViewController.setViewControllers([viewControllers[currentIndex]],
                                                    direction: .forward,
                                                    animated: true,
                                                    completion: nil)
    }
    
    
    
    /// 手动选中Controller
    /// - Parameters:
    ///   - index: <#index description#>
    ///   - animated: <#animated description#>
    func selectViewControllerAtIndex(index: Int , animated: Bool)  {
        
        let gotoViewController = viewControllerAtIndex(index: index)
        if let vc = gotoViewController {
                pageViewController.setViewControllers([vc], direction: index > currentIndex ? UIPageViewController.NavigationDirection.forward : UIPageViewController.NavigationDirection.reverse, animated: animated, completion: { (finished) in
                    self.currentIndex = index
                })
            
                
        }
       
    }
    
    
    fileprivate func viewControllerAtIndex(index: Int) -> UIViewController?{
        //Return the data View Controller for the given index
        if viewControllers.count == 0  || index > viewControllers.count {
            return nil
        }
       return viewControllers[index]
    }
    fileprivate func indexOfViewController(controller: UIViewController) -> Int{
        return viewControllers.firstIndex(of: controller) ?? NSNotFound
    }

}

//MARK: -扩展PageViewController实现数据源和代理协议


extension PageViewController: UIPageViewControllerDataSource,UIPageViewControllerDelegate{
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        // 显示前一个页面，保证数组不越界
        var index = indexOfViewController(controller: viewController)
        if index == 0 || index == NSNotFound{
            return nil
        }
        index-=1
        return viewControllerAtIndex(index: index)
       
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
         // 显示后一个视图
        var index = indexOfViewController(controller: viewController)
        if  index == NSNotFound{
            return nil
        }
        
        index+=1
        
        if index == viewControllers.count {
            return nil
        }
        
        return viewControllerAtIndex(index: index)

       }


       func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        let vc = pageViewController.viewControllers?.first
        currentIndex = indexOfViewController(controller: vc!)
        if completed {
            pageScrooCallBack?(currentIndex)
        }
           print("didFinishAnimating - 结束滚动")
        
       }
    

}
